package com.think.teaching.controller;

import java.io.IOException;
import java.net.URLEncoder;
import java.sql.Date;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;

import org.apache.commons.collections4.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.think.common.model.Result;
import com.think.common.model.ResultCode;
import com.think.common.utils.Common;
import com.think.common.utils.JSonUtil;
import com.think.common.utils.JWTUtils;
import com.think.common.utils.NetUtils;
import com.think.teaching.model.Article;
import com.think.teaching.model.College;
import com.think.teaching.model.Course;
import com.think.teaching.model.ExpStat;
import com.think.teaching.model.StudentInfo;
import com.think.teaching.model.TeacherInfo;
import com.think.teaching.model.TrainingResult;
import com.think.teaching.model.VrLesson;
import com.think.teaching.model.param.ExportExpStatParam;
import com.think.teaching.service.impl.ArticleServiceImpl;
import com.think.teaching.service.impl.ChapterServiceImpl;
import com.think.teaching.service.impl.CollegeServiceImpl;
import com.think.teaching.service.impl.CourseHistoryService;
import com.think.teaching.service.impl.CourseServiceImpl;
import com.think.teaching.service.impl.CourseUserServiceImpl;
import com.think.teaching.service.impl.ExamResultServiceImpl;
import com.think.teaching.service.impl.ExpRateSeviceImpl;
import com.think.teaching.service.impl.ExpStatServiceImpl;
import com.think.teaching.service.impl.StudentInfoServiceImpl;
import com.think.teaching.service.impl.TeacherInfoServiceImpl;
import com.think.teaching.service.impl.TrainingResultServiceImpl;
import com.think.teaching.service.impl.UserExamResultServiceImpl;
import com.think.teaching.service.impl.UserServiceImpl;
import com.think.teaching.service.impl.VrLessonServiceImpl;
import com.think.teaching.utils.DocumentHelper;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.val;
import lombok.experimental.var;

@RestController
@RequestMapping("/v1")
@Api(tags = "统计接口文档")
public class StatController {
	@Autowired
	private CourseServiceImpl courseServiceImpl;
	@Autowired
	private VrLessonServiceImpl vrLessonServiceImpl;
	@Autowired
	private ArticleServiceImpl articleServiceImpl;
	@Autowired
	private ExpStatServiceImpl expStatServiceImpl;
	@Autowired
	private CourseHistoryService courseHistoryService;

	@Autowired
	private StudentInfoServiceImpl studentInfoServiceImpl;

	@Autowired
	private TeacherInfoServiceImpl teacherInfoServiceImpl;

	@Autowired
	private CourseUserServiceImpl courseUserServiceImpl;

	@Autowired
	private ChapterServiceImpl chapterService;

	@Autowired
	private TrainingResultServiceImpl trainingResultServiceImpl;

	@Autowired
	private ExpRateSeviceImpl expRateSeviceImpl;

	@Autowired
	RedisTemplate redisTemplate;

	private final Integer multify = 5;

	private final String officialServer = "http://www.ilab-x.com/";

	//private final String testServer = "http://202.205.145.156:8017/";
	private final String testServer = "http://39.165.245.69:81/";


	@Value("${platform.reportPath}")
	private String PREFIX_PATH;
	
	@Value("${platform.client}")
	private String CLIENT_PREFIX;


	@Autowired
	private UserExamResultServiceImpl userExamResultServiceImpl;

	@Autowired
	private UserServiceImpl userServiceImpl;
	
	@Autowired
	private CollegeServiceImpl collegeServiceImpl;

	@ApiOperation("统计课程记录")
	@GetMapping("open/stat/course/{id}")
	public Result StatCourseDetailes(@PathVariable("id") Integer id) {
		Course course = courseServiceImpl.getById(id);
		if (course == null) {
			return Result.failure(ResultCode.COURSE_NOT_EXIST);
		}
		Map<String, Object> data = new HashedMap<String, Object>();
		data.put("visitCount", courseHistoryService.GetCourseVisitCount(id) * multify);
		data.put("studentCount", courseHistoryService.GetCourseVisitStudentCount(id) * multify);
		data.put("examCount", userExamResultServiceImpl.GetJoinExamStudentCount(id) * multify);
		return Result.success(data);
	}

	@ApiOperation("统计虚仿实验记录")
	@GetMapping("open/stat/vr/{id}")
	public Result StatVRLessonDetailes(@PathVariable("id") Integer id) {

		VrLesson lesson = vrLessonServiceImpl.getById(id);
		if (lesson == null) {
			return Result.failure(ResultCode.COURSE_NOT_EXIST);
		}
		Integer expCount = expStatServiceImpl.GetExpCount(id) * multify;
		Map<String, Object> data = new HashedMap<String, Object>();
		data.put("visitCount", courseHistoryService.GetChapterVisitCount(lesson.getChapterId()) * multify + expCount);
		data.put("studentCount", expStatServiceImpl.GetExpStudentCount(id) * multify);
		data.put("expCount", expCount);
		data.put("expResult", expStatServiceImpl.GetExpFinishCount(id) * multify);
		return Result.success(data);
	}

	@ApiOperation("统计虚仿实验记录")
	@GetMapping("open/stat/time/{id}")
	public Result StatVRLessonTime(@PathVariable("id") Integer id) {

		VrLesson lesson = vrLessonServiceImpl.getById(id);
		if (lesson == null) {
			return Result.failure(ResultCode.VR_LESSON_COURSE_NOT_EXIST);
		}
		return Result.success(expStatServiceImpl.GetStatTime(id));
	}

	@ApiOperation("统计虚仿实验记录")
	@GetMapping("open/stat/score/{id}")
	public Result StatVRLessonScore(@PathVariable("id") Integer id) {

		VrLesson lesson = vrLessonServiceImpl.getById(id);
		if (lesson == null) {
			return Result.failure(ResultCode.VR_LESSON_COURSE_NOT_EXIST);
		}
		return Result.success(expStatServiceImpl.GetStatScore(id));
	}

	@ApiOperation("统计虚仿实验记录")
	@GetMapping("open/stat/rate/{id}")
	public Result GetRateExp(@PathVariable("id") Integer id) {
		VrLesson lesson = vrLessonServiceImpl.getById(id);
		if (lesson == null) {
			return Result.failure(ResultCode.VR_LESSON_COURSE_NOT_EXIST);
		}
		return Result.success(expRateSeviceImpl.getAvgExpRate(id));
	}

	@ApiOperation("统计虚仿实验记录")
	@PostMapping("open/stat/rate/{id}")
	public Result PostRateExp(@RequestBody() Map<String, Object> data) {
		if (!data.containsKey("expId") || !data.containsKey("rate")) {
			return Result.failure(ResultCode.PARAM_NOT_COMPLETE);
		}

		Integer expId = (Integer) data.get("expId");
		Integer rate = (Integer) data.get("rate");
		VrLesson lesson = vrLessonServiceImpl.getById(expId);
		if (lesson == null) {
			return Result.failure(ResultCode.VR_LESSON_COURSE_NOT_EXIST);
		}
		if (rate < 0) {
			rate = 0;
		} else if (rate > 5) {
			rate = 5;
		}
		data.put("rate", rate);
		if (expRateSeviceImpl.setExpRate(expId, Common.GetCurrentAuthor().getUserId(), rate))
			return Result.success(data);
		else {
			return Result.failure(ResultCode.SYSTEM_DATABASE_ERROR);
		}
	}

	@ApiOperation("统计文章记录")
	@GetMapping("open/stat/article/{id}")
	public Result StatArticleDetailes(@PathVariable("id") Integer id) {
		Article article = articleServiceImpl.getById(id);
		if (article == null) {
			return Result.failure(ResultCode.COURSE_NOT_EXIST);
		}
		Map<String, Object> data = new HashedMap<String, Object>();
		data.put("visitCount", 10000);
		return Result.success(data);
	}

	SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");

	@ApiOperation("提交结束实验记录")
	@PostMapping("user/stat/endExp")
	public Result EndExpStat(@RequestBody() ExpStat data) {
		VrLesson expLesson = vrLessonServiceImpl.getById(data.getExpId());
//		ValueOperations valueOperations = redisTemplate.opsForValue();
		Course course = courseServiceImpl.getById(chapterService.getById(expLesson.getChapterId()).getCourseId());
		/* 从redis中获取验证码 */
//		String verificationCode = (String) valueOperations.get(Common.GetCurrentAuthor().getUserId()+"_" + course.getIlabAppId() + "_access_token");
		if (course == null) {
			return Result.failure(ResultCode.COURSE_NOT_EXIST);

		}
		if (data.getId() == null) {
			return Result.failure(ResultCode.EXP_STAT_NOTEXITS);
		}
		ExpStat old = expStatServiceImpl.getById(data.getId());
		if (old == null) {
			return Result.failure(ResultCode.EXP_STAT_NOTEXITS);

		}
		if (old.getStatus() == ExpStat.EXP_ENDED) {
			return Result.failure(ResultCode.EXP_STAT_NOTEXITS);
		}
		StudentInfo info = studentInfoServiceImpl.GetStudentInfoByUserId(Common.GetCurrentAuthor().getUserId());
		String name = "匿名用户";
		String idNum = "匿名用户";
		if (info != null) {
			name = info.getTrueName();
			idNum = info.getStudentId();
		} else {
			TeacherInfo teacherInfo = teacherInfoServiceImpl.GetTeacherByUserId(Common.GetCurrentAuthor().getUserId());
			if (teacherInfo != null) {
				name = teacherInfo.getName();
				idNum = teacherInfo.getTeacherId();
			}
		}

		old.setScore(data.getScore());
		old.setEndTime(new java.util.Date());
		old.setTimeUsed((old.getEndTime().getTime() - old.getStartTime().getTime()) / 1000);
		old.setStatus(ExpStat.EXP_ENDED);
		if (data.getReport().get("steps")!=null) {
			old.setSteps((ArrayList<Map<String, Object>>) data.getReport().get("steps"));
		}else {
			old.setSteps(new ArrayList<Map<String,Object>>());
		}

		if (data.getReport() != null) {
			old.setLearnContent(JSonUtil.toJson(data.getReport()));
		}

		sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
		String fileName = Common.GetCurrentAuthor().getUsername() + "-" + System.currentTimeMillis() + ".doc";
		try {
			String path = PREFIX_PATH + fileName;
			data.getReport().put("userName", name);
			data.getReport().put("studentId", idNum);
			data.getReport().put("startTime", sdf.format(old.getStartTime()));
			data.getReport().put("endTime", sdf.format(old.getEndTime()));
			DocumentHelper.CreatResourceWordByModelOutPdf("static/ExpReportTemp.doc", data.getReport(), path);
			System.out.println("生成报告路径====="+path);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String xilabRes = "";

		if (course.getIlabAppId() != null && course.getIlabAppSecret() != null) {
			ValueOperations valueOperations = redisTemplate.opsForValue();
			String key = Common.GetCurrentAuthor().getUserId() + "_" + course.getIlabAppId() + "_access_token";
			System.out.println(key);
			String accessToken = (String) valueOperations.get(key);
			if (accessToken != null) {
				Map<String, Object> maps = new HashMap<>();
				maps.put("username", Common.GetCurrentAuthor().getUsername());
				maps.put("title", expLesson.getExpName());
				maps.put("status", old.getSteps().size() >= 10?1:2);
				maps.put("score", old.getScore());
				maps.put("startTime", old.getStartTime().getTime());
				maps.put("endTime", old.getEndTime().getTime());
				maps.put("timeUsed", old.getTimeUsed());
				maps.put("appid", course.getIlabAppId());
				maps.put("originId", CLIENT_PREFIX + old.getId().toString());
				maps.put("steps", old.getSteps());
				if (data.getAddId() != null)
					maps.put("attachmentId", data.getAddId());
				String json = JSonUtil.toJson(maps);
				Map<String, String> header = new HashedMap<String, String>();
				header.put("Content-Type", "application/json");
				// TODO Auto-generated method stub
				try {
					xilabRes = NetUtils.doPost(String.format("%sopen/api/v2/data_upload?access_token=%s",
							course.getIlabAppId().equals(100400) ? testServer : officialServer,
							URLEncoder.encode(accessToken)), JSonUtil.toJson(maps), header);
					uploadReport(PREFIX_PATH + fileName, expLesson.getExpName() + "-实验报告",
							course.getIlabAppId(), CLIENT_PREFIX+ data.getId(), accessToken);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		}
		old.setAddId("/fileUpload/report/" + fileName);
		if (expStatServiceImpl.updateById(old)) {

			Map<String, String> result = new HashedMap<String, String>();
			result.put("report", "fileUpload/" + fileName);
			result.put("ilabx", xilabRes);
			return Result.success(result);
		}
		return Result.failure(ResultCode.SYSTEM_DATABASE_ERROR);
	}

	@ApiOperation("模拟实验记录")
	@PostMapping("user/stat/simulator")
	public Result SimulatorExpStat(@RequestBody() ExpStat data) {
		try {
			VrLesson expLesson = vrLessonServiceImpl.getById(data.getExpId());
			Course course = courseServiceImpl.getById(chapterService.getById(expLesson.getChapterId()).getCourseId());

			if (data.getExpId() == null) {
				return Result.failure(ResultCode.PARAM_NOT_COMPLETE);
			}
			if (data.getUserId() == null || data.getStartTime() == null || data.getEndTime() == null
					|| data.getScore() == null || data.getReport() == null) {
				return Result.failure(ResultCode.PARAM_NOT_COMPLETE);
			}
			StudentInfo info = studentInfoServiceImpl.GetStudentInfoByUserId(data.getUserId());
			if (info == null) {
				return Result.failure(ResultCode.STUDENT_NOT_EXIST);
			}
			String name = "匿名用户";
			String idNum = "匿名用户";
			if (info != null) {
				name = info.getTrueName();
				idNum = info.getStudentId();
			}
			data.setTimeUsed((data.getEndTime().getTime() - data.getStartTime().getTime()) / 1000);
			data.setStatus(ExpStat.EXP_ENDED);
			data.setSteps((ArrayList<Map<String, Object>>) data.getReport().get("steps"));

			sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
			String fileName = Common.GetCurrentAuthor().getUsername() + "-" + System.currentTimeMillis() + ".doc";

			try {
				String path = PREFIX_PATH + fileName;
				data.getReport().put("userName", name);
				data.getReport().put("studentId", idNum);
				data.getReport().put("startTime", sdf.format(data.getStartTime()));
				data.getReport().put("endTime", sdf.format(data.getEndTime()));
				data.setLearnContent(JSonUtil.toJson(data.getReport()));
				DocumentHelper.CreatResourceWordByModelOutPdf("static/ExpReportTemp.doc", data.getReport(), path);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			data.setAddId("/fileUpload/report/" + fileName);
			if (data.getSteps() == null) {
				data.setSteps(new ArrayList<Map<String,Object>>());
			}
			if (!expStatServiceImpl.save(data)) {
				return Result.failure(ResultCode.SYSTEM_DATABASE_ERROR);
			}
			String xilabRes = "";

			if (course.getIlabAppId() != null && course.getIlabAppSecret() != null) {
				ValueOperations valueOperations = redisTemplate.opsForValue();
				String key = Common.GetCurrentAuthor().getUserId() + "_" + course.getIlabAppId() + "_access_token";
				System.out.println(key);
				String accessToken = (String) valueOperations.get(key);
				if (accessToken != null) {
					Map<String, Object> maps = new HashMap<>();
					maps.put("username", Common.GetCurrentAuthor().getUsername());
					maps.put("title", expLesson.getExpName());
					maps.put("status", data.getSteps().size() >= 10?1:2);
					maps.put("score", data.getScore());
					maps.put("startTime", data.getStartTime().getTime());
					maps.put("endTime", data.getEndTime().getTime());
					maps.put("timeUsed", data.getTimeUsed());
					maps.put("appid", course.getIlabAppId());
					maps.put("originId", CLIENT_PREFIX +data.getId());
					maps.put("steps", data.getSteps());
					String json = JSonUtil.toJson(maps);
					Map<String, String> header = new HashedMap<String, String>();
					header.put("Content-Type", "application/json");
					try {
						xilabRes = NetUtils.doPost(String.format("%sopen/api/v2/data_upload?access_token=%s",
								course.getIlabAppId().equals(100400) ? testServer : officialServer,
								URLEncoder.encode(accessToken)), JSonUtil.toJson(maps), header);
						uploadReport(PREFIX_PATH + fileName, expLesson.getExpName() + "-实验报告",
								course.getIlabAppId(), CLIENT_PREFIX +data.getId(), accessToken);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
			Map<String, String> result = new HashedMap<String, String>();
			result.put("report", "fileUpload/" + fileName);
			result.put("ilabx", xilabRes);
			return Result.success(result);
		} catch (Exception e) {
			// TODO: handle exception
			return Result.failure(ResultCode.SYSTEM_INNER_ERROR,e.getMessage());

		}
		
	}

	@ApiOperation("提交实验记录")
	@PostMapping("user/stat/startExp")
	public Result PostExpStat(@RequestBody() ExpStat data) {
		VrLesson expLesson = vrLessonServiceImpl.getById(data.getExpId());
		if (expLesson == null) {
			return Result.failure(ResultCode.VR_LESSON_COURSE_NOT_EXIST);
		}
		if (data.getUserId() == null) {
			data.setUserId(Common.GetCurrentAuthor().getUserId());
		}
		ExpStat newData = expStatServiceImpl.GetLastRecord(data.getExpId(), Common.GetCurrentAuthor().getUserId());
		if (newData != null) {
			return Result.success(newData);
		}
		newData = new ExpStat();
		newData.setUserId(data.getUserId());
		newData.setExpId(data.getExpId());
		newData.setStartTime(new java.util.Date());
		newData.setStatus(2);
		if (expStatServiceImpl.save(newData)) {

			return Result.success(newData);
		}
		return Result.failure(ResultCode.SYSTEM_DATABASE_ERROR);
	}

	@ApiOperation("获取实验记录")
	@GetMapping("open/stat/exp/{page}/{count}")
	public Result GetExpStat(@RequestParam(required = false, defaultValue = "-1") Integer id,
			@PathVariable() Integer page, @PathVariable() Integer count) {
		if (vrLessonServiceImpl.getById(id) == null) {
			return Result.failure(ResultCode.VR_LESSON_COURSE_NOT_EXIST);
		}
		return Result.success(expStatServiceImpl.ListStat(id, page, count));
	}

	public void uploadReport(String filePath, String title, Integer appid, String originId, String ak) {
		String res="";
		NetUtils.postUpload(filePath,String.format("%sopen/api/v2/attachment_upload?access_token=%s&filename=%s&appid=%s&title=%s&remarks=xxx&originId=%s",
				appid.equals(100400) ? testServer : officialServer, URLEncoder.encode(ak),
				URLEncoder.encode("test.doc"), appid, URLEncoder.encode(title),originId));
	}

	@ApiOperation("获取用户实验记录")
	@GetMapping("user/stat/userExp/{page}/{count}")
	public Result GetUserExpStat(@RequestParam(defaultValue = "-1", required = false) Integer id,
			@PathVariable() Integer page, @PathVariable() Integer count) {
		if (id > 0 && vrLessonServiceImpl.getById(id) == null) {
			return Result.failure(ResultCode.VR_LESSON_COURSE_NOT_EXIST);
		}
		return Result.success(expStatServiceImpl.ListUserStat(id, page, count, Common.GetCurrentAuthor().getUserId()));
	}

	@ApiOperation("获取实验记录")
	@GetMapping("admin/stat/exp/{page}/{count}")
	public Result AdminGetExpStat(@RequestParam(required = false, defaultValue = "-1") Integer id,
			@PathVariable() Integer page, @PathVariable() Integer count) {
		return Result.success(expStatServiceImpl.ListStat(id, page, count));
	}

	@ApiOperation("获取实验记录")
	@GetMapping("admin/stat/course/exp/{page}/{count}")
	public Result AdminGetExpStatByCourse(@RequestParam(required = false, defaultValue = "-1") Integer id,
			@PathVariable() Integer page, @PathVariable() Integer count) {
		return Result.success(expStatServiceImpl.ListStatByCourse(id, page, count));
	}

	@ApiOperation("获取学生选课记录")
	@GetMapping("admin/stat/courseUser/{page}/{count}")
	public Result GetStatCourseUsers(@RequestParam(required = false, defaultValue = "-1") Integer course,
			@PathVariable() Integer page, @PathVariable() Integer count) {
		if (course > 0 && courseServiceImpl.getById(course) == null) {
			return Result.failure(ResultCode.COURSE_NOT_EXIST);
		}
		return Result.success(courseUserServiceImpl.ListCourseUser(count, page, course));
	}

	@ApiOperation("获取学生考试记录")
	@GetMapping("admin/stat/exam/{page}/{count}")
	public Result GetStatUserExam(@RequestParam(required = false, defaultValue = "-1") Integer course,
			@PathVariable() Integer page, @PathVariable() Integer count) {
		Map<String, Object> result = new HashedMap<String, Object>();
		result.put("total", userExamResultServiceImpl.count() * multify);
		result.put("outstanding", userExamResultServiceImpl.GeOutstandingCount(course) * multify);
		result.put("good", userExamResultServiceImpl.GetGoodCount(course) * multify);
		result.put("exam", userExamResultServiceImpl.ListExamResult(count, page, course));
		return Result.success(result);
	}

	@ApiOperation("获取学生实训记录")
	@GetMapping("admin/stat/traing/{page}/{count}")
	public Result GetStatUserTraining(@RequestParam(required = false, defaultValue = "-1") Integer course,
			@PathVariable() Integer page, @PathVariable() Integer count) {
		Map<String, Object> result = new HashedMap<String, Object>();
		result.put("total", trainingResultServiceImpl.count() * multify);
		result.put("outstanding", trainingResultServiceImpl.GetOutstandingCount(course) * multify);
		result.put("good", trainingResultServiceImpl.GetGoodCount(course) * multify);
		result.put("training", trainingResultServiceImpl.ListTrainingResult(count, page, course));
		return Result.success(result);
	}

	@ApiOperation("获取课程记录")
	@GetMapping("admin/stat/course/{page}/{count}")
	public Result GetStatCourse(@PathVariable() Integer page, @PathVariable() Integer count) {

		Map<String, Object> result = new HashedMap<String, Object>();
		result.put("total", courseServiceImpl.count() * multify);
		result.put("ban", courseServiceImpl.GetBanCount() * multify);
		result.put("duringReview", courseServiceImpl.GetDuringReviewCount() * multify);
		result.put("passedReview", courseServiceImpl.GetPassedReviewCount() * multify);
		result.put("courses", courseServiceImpl.ListCourseWithTagAndType(count, page, -1, 0, -1, -1, -1, -1));
		return Result.success(result);
	}

//	@ApiOperation("恢复实验报告")
//	@GetMapping("admin/stat/recover")
	public Result RecoverReport() {
		List<ExpStat> stats = expStatServiceImpl.GetExpFinishedReport();
		for (int i = 0; i < stats.size(); i++) {
			ExpStat stat = stats.get(i);
			if (stat.getAddId() == null || stat.getAddId().length() == 0 || stat.getLearnContent() == null
					|| stat.getLearnContent().length() == 0) {
				continue;
			}
			stat.setReport(JSonUtil.fromJson(stat.getLearnContent(), Map.class));
			if (stat.getReport() == null) {
				continue;
			}
			StudentInfo info = studentInfoServiceImpl.GetStudentInfoByUserId(stat.getUserId());
			if (info == null) {
				continue;
			}
			stat.getReport().put("studentId", info.getStudentId());
			stat.getReport().put("startTime", sdf.format(stat.getStartTime()));
			stat.getReport().put("endTime", sdf.format(stat.getEndTime()));
			try {
				DocumentHelper.CreatResourceWordByModelOutPdf("static/ExpReportTemp.doc", stat.getReport(), "E:/" + stat.getAddId());
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return Result.success();
	}
	@ApiOperation("导出学生实验记录")
	@PostMapping("admin/stat/export")
	public Result exportExpStat(@RequestBody()ExportExpStatParam data) {
		VrLesson lesson = vrLessonServiceImpl.GetVrLesson(data.getExpId());
		if (lesson == null) {
			return Result.failure(ResultCode.VR_LESSON_COURSE_NOT_EXIST);
		}
		Integer courseId = chapterService.GetChapter(lesson.getChapterId()).getCourseId();
		Course course = courseServiceImpl.getById(courseId);
		College college = collegeServiceImpl.getBaseMapper().getInfoById(course.getCollege());
		String school ="";
		String collegeName = "";
		if (college!=null) {
			collegeName = college.getCollegeName();
			school = college.getSchoolInfo().getName();
		}
		String fileName = System.currentTimeMillis()+".xlsx";
        List<List<String>> heads = new ArrayList<List<String>>();
        StringBuffer sb = new StringBuffer("实验记录：");
		sb.append("时间段：" +  (data.getStartTime()==null?"---":sdf.format(data.getStartTime()))+ "至" + (data.getEndTime()==null?"---":sdf.format(data.getEndTime())));

		List<String> headid = new ArrayList<String>();
	    headid.add(sb.toString());
	    headid.add("实验ID");
        List<String> head0 = new ArrayList<String>();
        head0.add(sb.toString());
        head0.add("实验名称");
        List<String> head1 = new ArrayList<String>();
        head1.add(sb.toString());
        head1.add("学生姓名");
        List<String> head2 = new ArrayList<String>();
        head2.add(sb.toString());
        head2.add("学号");
        List<String> head3 = new ArrayList<String>();
        head3.add(sb.toString());
        head3.add("所属单位/学校");
        List<String> head4 = new ArrayList<String>();
        head4.add(sb.toString());
        head4.add("开始时间");
        List<String> head5 = new ArrayList<String>();
        head5.add(sb.toString());
        head5.add("结束时间");
        List<String> head6 = new ArrayList<String>();
        head6.add(sb.toString());
        head6.add("实验用时");
        List<String> head7 = new ArrayList<String>();
        head7.add(sb.toString());
        head7.add("实验状态");
        List<String> head8 = new ArrayList<String>();
        head8.add(sb.toString());
        head8.add("实验得分");
        List<String> head9 = new ArrayList<String>();
        head9.add(sb.toString());
        head9.add("实验报告地址");
        List<String> head10 = new ArrayList<String>();
        head10.add(sb.toString());
        head10.add("实验记录详情");
        heads.add(headid);
        heads.add(head0);
        heads.add(head1);
        heads.add(head2);
        heads.add(head3);
        heads.add(head4);
        heads.add(head5);
        heads.add(head6);
        heads.add(head7);
        heads.add(head8);
        
        List<List<Object>> dataList = new ArrayList<List<Object>>();

		List<Map<String, Object>> records = expStatServiceImpl.ExportStat(data);
		final String s = school;
		records.stream().forEach(item->{
			List<Object> temp = new ArrayList<Object>();
			Integer status = (Integer)item.get("status");
			temp.add(item.get("id"));
			temp.add(item.get("expName"));
			temp.add(item.get("trueName"));
			temp.add(item.get("studentId"));
			temp.add(s);
			if(item.get("startTime")!=null)
			{
				temp.add(sdf.format(item.get("startTime")));
			}
			else {
				temp.add("---");
			}
			if(item.get("endTime")!=null)
			{
				temp.add(sdf.format(item.get("endTime")));
			}
			else {
				temp.add("---");
			}
			temp.add(item.get("timeUsed"));
			temp.add(status == 2?"未完成":"完成");
			temp.add(item.get("score"));
			temp.add(item.get("addId"));
			temp.add(item.get("learnContent"));
			System.out.println("实验个人数据====="+temp);
			dataList.add(temp);
		});
		System.out.println("实验数据====="+dataList);
		EasyExcel.write(PREFIX_PATH+ fileName).sheet("实验记录").head(heads).doWrite(dataList);

		return Result.success("/fileUpload/report/"+fileName);
	}

}
